package org.lanqiao.ssm.common.pay.alipay.core;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;


public class SignUtils {
	private final static Logger logger = LoggerFactory
			.getLogger(SignUtils.class);
	private static final String ALGORITHM = "RSA";

	private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

	private static final String DEFAULT_CHARSET = "UTF-8";

	public static String sign(String content, String privateKey) {
		try {
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
					Base64.decode(privateKey));
			KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
			PrivateKey priKey = keyf.generatePrivate(priPKCS8);

			java.security.Signature signature = java.security.Signature
					.getInstance(SIGN_ALGORITHMS);

			signature.initSign(priKey);
			signature.update(content.getBytes(DEFAULT_CHARSET));

			byte[] signed = signature.sign();

			return Base64.encode(signed);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	/**
	 * app支付后，支付宝回调接口验签
	 * 
	 * @param request
	 * @return
	 */
	public static void verifySign(Map<String, String> params) throws AlipayApiException {

		if (!AlipaySignature.rsaCheckV1(params, Config.ALIPAY_PUBLIC_KEY, Config.CHARSET)) {

			throw new AlipayApiException("verify sign fail.");
		}
		logger.info("验证通过！！");
		
	}
}
